package com.example.lib_audio.view

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.animation.addListener
import com.example.lib_audio.R
import com.example.lib_audio.audio.AudioController
import com.example.lib_audio.eventbus.AudioLoadEvent
import com.example.lib_audio.eventbus.AudioPauseEvent
import com.example.lib_audio.eventbus.AudioStartEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SongWaveView(context:Context,attrs:AttributeSet?):View(context,attrs) {
    private  var wave_color = 0
    private var wave_speed = 0
    private var waveWidth = dp2px(5)
    private var mSpace = dp2px(3)
    private var waveHeight = dp2px(20)
    private val mPaint: Paint by lazy {
        Paint().apply {
            isAntiAlias = true
            color = wave_color
        }
    }

    init {

        //解析属性
        parseAttr(attrs)

        //注册EventBus
        EventBus.getDefault().register(this)
    }

    private fun parseAttr(attrs: AttributeSet?){
        context.obtainStyledAttributes(attrs,R.styleable.SongWaveView).apply {
            wave_color = getColor(R.styleable.SongWaveView_wave_color,Color.YELLOW)
            wave_speed = getInteger(R.styleable.SongWaveView_wave_speed,600)

            recycle()
        }
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var mWidth = MeasureSpec.getSize(widthMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        if(widthMode != MeasureSpec.EXACTLY){
            mWidth = (3*waveWidth+2*mSpace).toInt()
        }


        var mHeight = MeasureSpec.getSize(heightMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)

        if(heightMode != MeasureSpec.EXACTLY){
            mHeight = waveHeight.toInt()
        }

        setMeasuredDimension(mWidth,mHeight)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        waveWidth = (width-mSpace*2)/3f

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //绘制三根柱子
        var left = 0f
        var right = waveWidth
        var bottom = height.toFloat()
        canvas?.drawRoundRect(left,(1-changeTops[0])*bottom,right,bottom,dp2px(10),dp2px(10),mPaint)

        canvas?.drawRoundRect(left+waveWidth+mSpace,(1-changeTops[1])*bottom,right+waveWidth+mSpace,bottom,dp2px(10),dp2px(10),mPaint)

        canvas?.drawRoundRect(width.toFloat()-waveWidth,(1-changeTops[2])*bottom,width.toFloat(),bottom,dp2px(10),dp2px(10),mPaint)


    }

    private var changeTops = arrayListOf(0f,0f,0f)
    private var anims = arrayListOf<Animator>()

    private val animatorSet:AnimatorSet by lazy {
        for (i in 0..2){
            val anim = ValueAnimator.ofFloat(0.2f,1f).apply {
                repeatMode = ValueAnimator.REVERSE
                repeatCount = ValueAnimator.INFINITE
                duration = 500
                addUpdateListener {
                    changeTops[i] = it.animatedValue as Float
                    invalidate()
                }
                startDelay  = i*200L
            }
            anims.add(anim)
        }

        AnimatorSet().apply {
            playTogether(anims)
        }
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        if(visibility == VISIBLE && AudioController.getInstance()?.isPlaying() == true){
            Log.v("wjb","$this VISIBLE")
            animatorSet.start()
        }else if(visibility == INVISIBLE && AudioController.getInstance()?.isPlaying() == true){
            Log.v("wjb","$this yes")
        }else{
            Log.v("wjb","$this INVISIBLE")
            animatorSet.pause()
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoad(event:AudioLoadEvent){
        Log.v("wjb","onLoad")
            animatorSet.start()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onStart(event:AudioStartEvent){
            animatorSet.resume()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPause(event:AudioPauseEvent){
            animatorSet.pause()
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        EventBus.getDefault().unregister(this)
    }

    override fun toString(): String {
        return "${this.hashCode()}"
    }


    fun dp2px(dp:Int) = resources.displayMetrics.density*dp

}